<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2017/1/1 18:51
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */
require_once FCPATH . '/application/third_party/wechat/include.php';

use Wechat\WechatPay;

class Callback extends CI_Controller
{

    private $pay_log = '';

    private $dateTime = '';

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
        $this->pay_log = '/var/pay/Wechat-' . date('Y-m') . '.log';
        $this->dateTime = date('Y-m-d H:i:s');
    }

    public function index()
    {

    }

    public function notify()
    {

        $pay_ret = false;
        $sn = '';
        $log_error = '';
        $data = [];
        $return = [
            'return_code' => 'FAIL',
            'return_msg' => ''
        ];

        $wechat = new WechatPay();
        do {
            $wechat->appid = WX_APPID;          // wx_app_appid
            $wechat->mch_id =  WX_MCHID;
            $wechat->partnerKey = WX_APIKEY;

            $res = $wechat->getNotify();
            if (!$res) {
                $log_error = '鉴权错误';
                $return['return_msg'] = '鉴权失败';
                break;
            }

            $data = $res;
            $data['status'] = 5;

            // 1. 判断返回状态
            if ($res['return_code'] == 'SUCCESS') {
                $sn = $res['out_trade_no'];

                if (empty($data['total_fee'])) {
                    $return['return_msg'] = '商品总金额错误';
                    break;
                }

                if ($res['result_code'] == 'SUCCESS') {
                    // 2. 跟当前订单进行对比
                    $orderDb = clone($this->db);
                    $query = $orderDb->get_where('user_order', ['sn' => $data['out_trade_no']]);
                    $order = $query->row_array();
                    if (empty($order)) {
                        $log_error = '无此订单存在';
                        $return['return_msg'] = '订单不存在';
                        break;
                    }

                    // $totalPrice = intval($order['totalPrice'] * 100);
                    $totalPrice = 1;
                    if ($totalPrice != $res['total_fee']) {
                        $log_error = '商品金额错误';
                        $return['return_msg'] = '商品金额不符';
                        break;
                    }

                    if ($order['payStatus'] == 6) {
                        $log_error = '重复支付订单';
                        $return['return_msg'] = '商品已支付';
                        break;
                    }

                    // 3. 修改订单状态
                    $modifyData = [
                        'payWay' => 2,
                        'payStatus' => 6,
                        'status' => 'Pending'
                    ];
                    $orderDb2 = clone($this->db);
                    $orderDb2->where('sn', $data['out_trade_no']);
                    $orderDb2->update('user_order', $modifyData);

                    if ($orderDb2->affected_rows()) {
                        $pay_ret = true;
                        $data['status'] = 6;
                        $return['return_code'] = 'SUCCESS';
                    }
                } else {
                    $return['return_msg'] = 'Failed';
                }

                $db = clone($this->db);
                if (!$pay_ret) {
                    $data['error_msg'] = !empty($return['return_msg']) ? $return['return_msg'] : '支付失败';
                    $data['error_code'] = 'FAILED';
                }
                $db->insert('user_order_wechat', $data);

            } else {
                $log_error = '返回数据异常';
            }
        } while(false);

        if ($pay_ret) {
            file_put_contents($this->pay_log, '['.date('Y-m-d H:i:s').'] SUSSCESS SN: ' . $sn . PHP_EOL, FILE_APPEND);
        } else {
            file_put_contents($this->pay_log, '['.date('Y-m-d H:i:s').'] FAILED Error: ' . $log_error . PHP_EOL, FILE_APPEND);
            !empty($data) && file_put_contents($this->pay_log, var_export($data, true) . PHP_EOL, FILE_APPEND);
        }

        $wechat->replyXml($return);
    }
}